import React, { Component } from 'react'
import axios from 'axios'
import '../style/checkrole.scss'
import { Table, Tag, Space, Button, Popconfirm, Modal, Form, Input, Checkbox,notification  } from 'antd';
import { nanoid } from 'nanoid'

export default class CheckRole extends Component {
    contentRef = React.createRef();
    systemRef = React.createRef();
    memberRef = React.createRef();
    articleRef = React.createRef();
    state = {
        listData: [
        ],
        isModalVisible: false,
        itemId: 0,
    }
    hideModle = () => {
        this.setState({ isModalVisible: false })
    }
    showModle = (id) => {
        return () => {
            console.log(id);
            this.setState({ isModalVisible: true, itemId: id })
        }

    }
    //编辑
    editRole = () => {
        const { listData,itemId } = this.state
        if (this.contentRef.current.state.value === '') {
            alert("角色名不能为空")
        } else {
            axios({
                method: "post",
                url: "/api1/editrole?timetamp=" + new Date().getTime(),
                params: {
                    id: itemId,
                    content: this.contentRef.current.state.value,
                    author: JSON.stringify({
                        "system": this.systemRef.current.state.checked,
                        "member": this.memberRef.current.state.checked,
                        "article": this.articleRef.current.state.checked,
                    })
                }
            }).then(res => {
                console.log(res.data);
                const newList = listData.map((item)=>{
                    if(item.id === itemId){
                        let authorArr = [
                            JSON.parse(res.data.author).system ? "系统管理" : '',
                            JSON.parse(res.data.author).member ? "会员管理" : '',
                            JSON.parse(res.data.author).article ? "文章管理" : '',
                        ]
                        return {key: nanoid(),...res.data,roleauthor:authorArr,rolename:res.data.content}
                    } else {
                        return item
                    }
                })
                this.setState({listData:newList,isModalVisible:false})
                notification.open({
                    message: '修改成功',
                    description:
                      '太强了',
                    onClick: () => {
                      console.log('Notification Clicked!');
                    },
                  });
            })
        }

    }
    //删除
    deleteItem = (id) => {
        const { listData } = this.state
        return () => {
            axios({
                method: "post",
                url: "/api1/delrole?timetamp=" + new Date().getTime(),
                params: {
                    id: id
                }
            }).then(res => {
                console.log(res.data);
                //删除指定id的todo对象
                const newList = listData.filter((item) => {
                    return item.id !== id
                })
                //更新状态
                this.setState({ listData: newList })
            })
        }
    }
    componentDidMount() {
        const { listData } = this.state
        axios({
            method: "get",
            url: "/api1/data?timetamp=" + new Date().getTime(),
        }).then(res => {
            console.log(res.data);
            this.setState({ listData: res.data })
            let newList = res.data.map((item, index) => {
                let authorArr = [
                    JSON.parse(item.roleauthor).system ? "系统管理" : '',
                    JSON.parse(item.roleauthor).member ? "会员管理" : '',
                    JSON.parse(item.roleauthor).article ? "文章管理" : '',
                ]
                return { key: nanoid(), ...item, roleauthor: authorArr }
            })
            console.log(newList);
            this.setState({ listData: newList, haveData: true })
        })
    }
    render() {
        const { Column, ColumnGroup } = Table;
        const { listData, isModalVisible } = this.state
        return (!this.state.haveData ? <p className="loading" style={{ fontSize: "30px" }}>loading</p> : (
            <div id="check-role">
                <Table className="list" dataSource={listData} pagination={{ defaultPageSize: "5" }}>
                    <Column title="id" dataIndex="id" key={nanoid()} />
                    <Column title="名称" dataIndex="rolename" key={nanoid()} />
                    <Column title="权限" dataIndex="roleauthor" key={nanoid()}
                        render={roleauthor => (
                            <>
                                {roleauthor.map(tag => (
                                    tag === "" ? "" : <Tag color="blue" key={nanoid()} className="tag">
                                        {tag}
                                    </Tag>
                                ))}
                            </>
                        )}
                    />
                    <Column title="操作" dataIndex="action" key={nanoid()}
                        render={(text, record) => (
                            <Space size="middle">
                                <Button type="primary" onClick={this.showModle(record.id)}>编辑</Button>
                                <Popconfirm placement="top" title='确定删除吗？' onConfirm={this.deleteItem(record.id)} okText="Yes" cancelText="No">
                                    <Button danger >删除</Button>
                                </Popconfirm>
                            </Space>
                        )}
                    />
                </Table>
                <Modal title="编辑角色" visible={isModalVisible} onOk={this.editRole} onCancel={this.hideModle}>
                    <Form.Item
                        label="角色名称"
                        className="user-name flex_start"
                    >
                        <Input className="user-in" size='large' ref={this.contentRef} />
                    </Form.Item>
                    <Form.Item
                        label="权限"
                        className="user-author flex_start"
                    >
                        <Checkbox ref={this.systemRef}>系统设置</Checkbox>
                        <Checkbox ref={this.memberRef}>会员管理</Checkbox>
                        <Checkbox ref={this.articleRef}>文章管理</Checkbox>

                    </Form.Item>
                </Modal>
            </div>
        ))
    }
}
